package nsu.edu.zsq.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import nsu.edu.zsq.bean.SchRoom;
import nsu.edu.zsq.bean.SchRoomExample;
import nsu.edu.zsq.bean.SchRoomExample.Criteria;
import nsu.edu.zsq.bean.TchCourse;
import nsu.edu.zsq.dao.SchRoomMapper;
import nsu.edu.zsq.exception.ParamException;
import nsu.edu.zsq.service.SchRoomManageService;

/** 
* Description: 学校教室管理的service实现类<br>
*/
@Service
public class SchRoomManageServiceImpl implements SchRoomManageService {
    
    @Autowired
    private SchRoomMapper schRoomMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveCourseToSchRoom(TchCourse tchCourse) {
        if (tchCourse.getRoomName() == null || tchCourse.getRoomName().length() <= 0) {
            return;
        }
        // 1.判断这个教室是否被使用
        SchRoomExample example = new SchRoomExample();
        example.createCriteria().andRoomNameEqualTo(tchCourse.getRoomName()).andCourseWeekEqualTo(String.valueOf(tchCourse.getStartDay()))
            .andCourseTimeEqualTo(String.valueOf(tchCourse.getStartTime())).andCourseIdNotEqualTo(0);
        boolean isUsed = schRoomMapper.countByExample(example) > 0;
        if (isUsed) {
            throw new ParamException("与已有的教室课程时间安排冲突");
        } else {
            // 2.开始保存教室的课程信息
            // 这里给教室课程保存的是教师课程的id，以后查教室中上课的课程时，就到教师课程表中查课程信息
            // 同时，设置自习室状态为否
            SchRoom schRoom = SchRoom.builder().courseId(tchCourse.getId()).isStudyRoom(0).build();
            SchRoomExample saveExample = new SchRoomExample();
            saveExample.createCriteria().andRoomNameEqualTo(tchCourse.getRoomName()).andCourseWeekEqualTo(String.valueOf(tchCourse.getStartDay()))
                .andCourseTimeEqualTo(String.valueOf(tchCourse.getStartTime()));
            schRoomMapper.updateByExampleSelective(schRoom, saveExample);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCourseFromSchRoom(int tchCourseId, int courseType) {
        // 移除课程信息的同时，设置为自习室状态
        SchRoom schRoom = SchRoom.builder().courseId(0).isStudyRoom(1).build();
        SchRoomExample example = new SchRoomExample();
        Criteria createCriteria = example.createCriteria();
        createCriteria.andCourseIdEqualTo(tchCourseId);
        if (courseType == 1) {
            // 如果是必修，则表明上课时间不会是910节
            createCriteria.andCourseTimeNotEqualTo("910");
        } else {
            createCriteria.andCourseTimeEqualTo("910");
        }
        schRoomMapper.updateByExampleSelective(schRoom, example);
    }
}
